-- FruitTreeM
-- Create by panyl
-- 果树模块

module("FruitTreeM", package.seeall);

-- 所有的果实信息
local fruits = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    fruits = {};

    -- 转换下fruits信息表
    local fruits_CSV = get_fruits_CSV();
    for i = 1, #fruits_CSV do
        local classId = fruits_CSV[i].class_id;

        fruits[classId] = fruits[classId] or {};

        table.insert(fruits[classId], fruits_CSV[i]);
    end

    -- 排序
    for classId, arr in pairs(fruits) do
        table.sort(arr, function(a, b)
            return a.id < b.id;
        end);
    end

    fruits_CSV = {};
end

-- 模块初始化
function init()
    loadCsv();
end

-- 计算果树奖励
function calcFruitBonus(pos)
    local grid = DungeonM.getGridByPos(pos);

    -- 如果不是果树
    if grid.type ~= GRID_TYPE_FRUIT then
        trace("FruitTreeM", "格子%d不是果树。", pos);
        return {};
    end

    local arr = fruits[grid.fruit];
    if not arr or grid.state == GRID_STATE_DISABLE then
        trace("FruitTreeM", "果树失效了。");
        return {};
    end

    -- 按权重随机抽取一个果实
    local rand = DungeonM.getRandSeed("take_fruit");
    local sum = 0;
    for _, row in pairs(arr) do
        sum = sum + row["weight"];
    end

    rand = rand % sum;
    sum = 0;
    local fruit;
    for _, row in pairs(arr) do
        sum = sum + row["weight"];

        if sum > rand then
            fruit = row;
            break;
        end
    end
    local bonus = fruit.apply;

    if type(bonus) == "table" then
        return bonus;
    end

    if  type(bonus) == "string" and
        string.startWith(bonus, "formula_") then
        local formula = string.sub(bonus, string.len("formula_") + 1);
        return FormulaM.invoke(formula, ME.user, grid.fruit);
    end
end

-- 采摘果实
function takeFruit(pos)
    local grid = DungeonM.getGridByPos(pos);

    -- 如果不是果树
    if grid.type ~= GRID_TYPE_FRUIT then
        trace("FruitTreeM", "格子%d不是果树。", pos);
        return false;
    end

    -- 奖励
    local bonus = calcFruitBonus(pos);
    if type(bonus) ~= "table" then
        return false;
    end

    local round = CombatM.getRound();
    for key, info in pairs(bonus) do
        local value = table.deepcopy(info); -- 这里需要copy一份，免得后面修改了

        if key == "bonus" then
            -- 奖励
            BonusM.doBonus(value, "fruit");
        elseif key == "debuff" then
            if value[4] ~= -1 then
                value[4] = round + value[4];
            end

            PropM.recordDebuff(ME.user, value);
        elseif key == "buff" then
            if value[4] ~= -1 then
                value[4] = round + value[4];
            end

            PropM.recordBuff(ME.user, value);
        elseif key == "prop" then
            if value[4] ~= -1 then
                value[4] = round + value[4];
            end

            PropM.record(ME.user, value, "mixed");
        end
    end

    -- 坏掉的野果
    if grid.bad_fruit and grid.drop_rate then
        local arr = grid.bad_fruit;
        local rate = grid.drop_rate;
        local rand = DungeonM.getRandSeed("bad_fruit") % 100;

        -- 如果是第一次
        if CombatStatM.getFieldStat("bad_fruit") <= 0 then
            rate = 100;
        end

        if rand < rate then
            BonusM.doBonus(arr, "bad_fruit");

            EventMgr.fire(event.COMM_BUILDING_BONUS, {
                ["pos"]   = pos,
                ["type"]  = grid.type,
                ["bonus"] = { ["bonus"] = arr },
            });
        end

        CombatStatM.addFieldStat("bad_fruit", 1);
    end

    -- 删除
    grid.fruit = nil;

    -- 改变状态
    grid:changeState(GRID_STATE_DISABLE);

    -- 抛出事件
    EventMgr.fire(event.TAKE_FRUIT, {["pos"] = pos, ["bonusInfo"] = bonus,});

    -- 通知建筑事件完成
    EventMgr.fire(event.BUILDING_EVENT_DONE, {["pos"] = pos,});

    if DungeonM.isCostRound(grid) then
        -- 抛出一个回合事件
        EventMgr.fire(event.COMBAT_ROUND, { ["pos"] = pos, ["isDelay"] = true });
    end

    return true;
end
